package com.hccl.service;

import com.hccl.SMSDetector.SimilarSMSFinder;
import com.hccl.controller.ClusteringController;
import okhttp3.*;
import org.apache.log4j.Logger;
import org.json.JSONObject;
import java.io.*;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

/**
 * Created by sunjia on 2018/7/13.
 */

public class TaskThread implements Runnable{

    static OkHttpClient client = new OkHttpClient.Builder().connectTimeout(500, TimeUnit.MILLISECONDS)
            .writeTimeout(500, TimeUnit.MILLISECONDS).readTimeout(500, TimeUnit.MILLISECONDS).build();//设置超时
    public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
    private static String url=null;

    private static final Logger logger = Logger.getLogger(TaskThread.class);

    static {
        Properties property = new Properties();
        try {

            property.load(new FileInputStream("application.properties"));
            url = property.getProperty("callback.url","http://ip:port/gxb.service/postTxtClusterResult");
        } catch (Exception e) {
            System.err.println("Loading configuration failed, please check. Using default parameters.");
            System.exit(-1);
        }
    }

    @Override
    public void run() {

        while (true) {
            try {
                JSONObject task = ClusteringController.blockingQueue.take(); //取任务
                JSONObject result = SimilarSMSFinder.doClustering(task.toString());
                postMess(url, result.toString());
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    public static void postMess(String url, String json) {

        //POST提交Json数据
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
            String resultStr = response.body().string();
            logger.info("after execute get result:{}" + resultStr);
        } catch (IOException e) {
            logger.error("HttpJob execute error! problem url:{}" + url, e);
        } finally {
            response.body().close();
        }
    }

}
